library(shiny)
library(DT)
library("dplyr")
library("ggplot2")
library("plotly")
library("zoo")

bdate <- as.Date("2021-05-21", tryFormats = c("%Y-%m-%d"))
bwt <- 54

wtdt <- read.csv("https://gitee.com/shuguangS/wt/raw/master/wt.csv") %>%
  mutate(
    date = as.Date(date, tryFormats = c("<%Y-%m-%d")),
    week = difftime(date, bdate, units = "week"),
    ch = Weight - bwt,
    pch = (Weight - bwt)/bwt
  ) %>%
  select(date, week, Weight, pch, ch) %>%
  relocate(date, week, Weight, ch, pch)

wtdtpch <- wtdt %>%
  dplyr::arrange(date) %>%
  slice(-1) %>%
  mutate(
    pchsp = predict(smooth.spline(week, pch))$y
  ) %>%
  select(date, pchsp) %>%
  dplyr::full_join(wtdt, by = "date")

wtdtstat <- wtdt %>%
  dplyr::arrange(date) %>%
  mutate(
    wt = Weight - bwt,
    # ma3 = stats::filter(wt, filter = rep(1/3, 3), sides = 1),
    ## ma5 = stats::filter(wt, filter = rep(1/5, 5), sides = 1),
    ma7 = stats::filter(wt, filter = rep(1/7, 7), sides = 1),
    # md3 = zoo::rollmedian(wt, k = 3, fill = NA, align = "right"),
    ## md5 = zoo::rollmedian(wt, k = 5, fill = NA, align = "right"),
    md7 = zoo::rollmedian(wt, k = 7, fill = NA, align = "right"),
  )

wtdtstat <- wtdtstat %>%
  slice(-1) %>%
  mutate(
    sp = predict(smooth.spline(week, wt))$y
  ) %>%
  select(date, sp) %>%
  dplyr::full_join(wtdtstat, by = "date") %>%
  select(-wt) %>%
  tidyr::pivot_longer(c(starts_with("ma"), starts_with("md"), "sp"),
                      names_to = "stat", names_prefix = NULL, names_sep = NULL,
                      values_to = "value", values_drop_na = FALSE) %>%
  mutate(stat = factor(stat),
         stat = dplyr::recode(stat,
                              ma3 = "3 Day Moving Average",
                              ma5 = "5 Day Moving Average",
                              ma7 = "7 Day Moving Average",
                              md3 = "3 Day Meian",
                              md5 = "5 Day Meian",
                              md7 = "7 Day Meian",
                              sp = "Smooth Line",
                              wt = "Weight Line"
                              ))


ui <- navbarPage(
  "Trend of Weight",
  collapsible = TRUE, inverse = TRUE,
  # theme = shinythemes::shinytheme("spacelab"),
  ## Application title
  ## titlePanel("Trend of Weight"),

  tabPanel("Table",
           DT::dataTableOutput('tbl')),

  tabPanel("Weight",
           plotlyOutput("wtplot")),

  tabPanel("Percent Change from Baseline",
           plotlyOutput("pchplot"))
)

server <- function(input, output, session) {

  output$tbl = DT::renderDataTable(
  {datatable(wtdt %>%
               dplyr::arrange(desc(date))) %>%
     formatRound("week",
                 digits = 1) %>%
     formatRound("ch",
                 digits = 1) %>%
     formatPercentage('pch',
                      digits = 1)
  })

  output$wtplot <- renderPlotly({
    wtdtstat %>% plot_ly() %>%
      add_markers(data = wtdt, x = ~week, y = ~ch, name = "Change") %>%
      add_lines(data = wtdtstat, x = ~week, y = ~value, color = ~stat, line=list(width=2)) %>%
      layout(yaxis = list(title = "Change from Basline"),
             xaxis = list(title = "Week")) %>%
      layout(legend = list(orientation = "h", y = -.2, xanchor = "center", x = 0.5))
    ## %>%
    ##   rangeslider()
  })


  output$pchplot <- renderPlotly({
    wtdtpch %>% plot_ly() %>%
      add_markers(x = ~week, y = ~pch, name = "Change%") %>%
      add_lines(x = ~week, y = ~pchsp, name="smooth.spline", line=list(color="orange", width=2)) %>%
      layout(yaxis = list(title = "Percent Change from Basline", tickformat = ".0%"),
             xaxis = list(title = "Week")) %>%
      layout(legend = list(orientation = "h", y = -.2, xanchor = "center", x = 0.5))
    ## %>%
    ##   rangeslider()
  })
}

shinyApp(ui, server)
